'use strict';
// const hmac = require("hmac")
// const hashlib = require("hashlib")
const crypto = require('crypto');

module.exports = {
	/**
	 * XXXnameXXX
	 * @url client/xcxzf/kh/pay.js 前端调用的url参数地址
	 * data 请求参数
	 * @param {String} params1  参数1
	 */
	main: async (event) => {
		let user_order_success = true;
		let {
			data = {}, userInfo, util, filterResponse, originalParam
		} = event;
		let {
			customUtil,
			uniID,
			config,
			pubFun,
			vk,
			db,
			_
		} = util;
		let {
			uid,
			pid,
			openid,
			out_trade_no,
			user_id,
			provider,
			total_fee,
			subject,
			bean_number,
			body,
			type,
			UUID,
			transaction_id,
			recharge_balance,
			log_No,
			trade_no,
			os_name,
		} = data;
		let res = {
			code: 0,
			msg: ""
		};
		// 业务逻辑开始-----------------------------------------------------------

		console.log('pay中的data', data);
		if (!out_trade_no || !total_fee) {
			user_order_success = false;
			return user_order_success;
		}

		//修改充值记录订单，状态为已支付，并记录实付金额，微信支付订单号等
		const update_order = await db.collection('a_recharge').where({
			out_trade_no: out_trade_no
		}).update({
			openid: openid,
			shifu_amount: total_fee,
			transaction_id: transaction_id,
			pay_status: 1,
			_add_time: data._add_time,
			_add_time_str: data._add_time_str,
			log_No: log_No,
			trade_no: trade_no,
			os_name: os_name,
		})

		console.log('修改订单信息');


		if (data.subject == "充值金豆") {
			console.log("充值成功！", openid);
			//如果修改成功，给用户增加金豆数量
			//此方法腾讯云和阿里云都支持
			let newInfo = await vk.baseDao.updateAndReturn({
				dbName: "uni-id-users",
				whereJson: {
					_id: user_id
				},
				dataJson: {
					had_youhui: true, //had_youhui可以判断用户是否付费过，便于付费用户数量统计
					balance: _.inc(bean_number)
				}
			});

			console.log('添加金豆数量');


			//添加金豆收支明细
			const add_jindou = await db.collection('a_jindou_detail').add({
				user_id: user_id,
				nickname: newInfo.nickname || "未绑定",
				change_num: bean_number, //增加的金豆数量
				changed_num: newInfo.balance, //支付后金豆余额
				change_reason: "支付" + total_fee + "分钱充值" + bean_number + "金豆",
				type: "income", //类型：expend:支出,income:收入。
				appid: newInfo.appid || "",
				appname: newInfo.appname || "",
				_add_time: data._add_time,
				_add_time_str: data._add_time_str,
				os_name: os_name,
			})

			console.log('添加金豆收支明细');
		} else {
			let addtime = 0;
			//【开通会员】这个类型是为了兼容老版本的年费会员
			if (data.subject == "开通会员") {
				addtime = 31536000000 //365天
			}
			if (data.subject == "年度会员") {
				addtime = 31536000000 //365天
			}
			if (data.subject == "季度会员") {
				addtime = 7776000000 //90天
			}
			if (data.subject == "月度会员") {
				addtime = 2592000000 //30天
			}
			//先查询用户信息，是否已是会员
			let getres = await db.collection('uni-id-users').doc(user_id).field({
				plus_expire_time: true
			}).get()

			var nowtime = new Date().getTime()
			const plus_expire = getres.data[0].plus_expire_time
			if (plus_expire * 1 < nowtime * 1) {
				let new_expire_time = nowtime * 1 + addtime;
				//如果会员已到期，会员时间就是当前时间+addtime
				let updateVip = await db.collection('uni-id-users').doc(user_id).update({
					plus_type: 1,
					plus_expire_time: new_expire_time
				})
			} else {
				console.log("修改用户会员到期时间");
				let new_expire_time2 = plus_expire * 1 + addtime
				//如果会员没有到期，会员时间就是到期时间+addtime
				let updateVip2 = await db.collection('uni-id-users').doc(user_id).update({
					plus_expire_time: new_expire_time2
				})
			}
		}


		// 云函数内调用其他云函数或云对象内的函数,进行付费数据回传。
		let callRes = await vk.callFunction({
			name: "hedian",
			url: 'client/user/pub/callback',
			data: {
				out_trade_no: out_trade_no, //充值订单号
				total_fee: total_fee, //支付金额
				_add_time: data._add_time,
				_add_time_str: data._add_time_str
			},
		});
		console.log(callRes)


		// 业务逻辑结束-----------------------------------------------------------

		return user_order_success;





	}
}